package com.ds.common.org.expression.person;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import java.util.StringTokenizer;

import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.Function;
import com.ds.org.OrgManager;
import com.ds.org.Person;
import com.ds.org.Role;
import com.ds.server.OrgManagerFactory;

/**
 * 取得指定某些岗位下的所有人员，已包含人员去重功能。
 * <p>Title: JDSORG组织机构中间件</p>
 * <p>Description: </p>
 * <p>Copyright: jds Copyright (c) 2003-2008</p>
 * <p>Company: www.justdos.net</p>
 * @author wenzhangli
 * @version 2.0
 */
public class GetPersonByPersonPositions extends Function {
	public GetPersonByPersonPositions() {
		numberOfParameters = 1;
	}

	public void run(Stack stack) throws ParseException
	{
		checkStack(stack); // check the stack

		Object param2 = stack.pop(); 
		stack.push(perform( param2));
	}

	protected Person[] perform(Object param1) throws ParseException {
		if (param1 == null) {
			return new Person[0];
		}
		//String，“:”隔开
		if (param1 instanceof String) {
			OrgManager orgManager = OrgManagerFactory.getOrgManager();
			
			String positionNames = (String)param1;
			StringTokenizer st = new StringTokenizer(positionNames, ":");
			List result = new ArrayList();
			while(st.hasMoreTokens()) {
				Person[] persons = (Person[]) orgManager.getPersonsByPersonPositionName(st.nextToken()).toArray(new Person[0]);
				for (int i = 0; i < persons.length; i++) {
					if (!result.contains(persons[i])) {
						result.add(persons[i]);
					}
				}
			}
			return (Person[])result.toArray(new Person[result.size()]);
		}
		
		//PersonPosition数组
		if (param1 instanceof Role[]) {
			OrgManager orgManager = OrgManagerFactory.getOrgManager();
			Role[] positions = (Role[]) param1;
			List result = new ArrayList();
			for (int i = 0, m=positions.length; i < m; i++) {
				String positionId = positions[i].getRoleId();
				Person[] persons = (Person[]) orgManager.getPersonsByPersonPositionName(positionId).toArray(new Person[0]);
				for (int j = 0, n=persons.length; j < n; j++) {
					if (!result.contains(persons[j])) {
						result.add(persons[j]);
					}
				}
			}
			return (Person[])result.toArray(new Person[result.size()]);
		}
		
 		throw new ParseException("Invalid parameter type in:" + this.getClass().getName() + ", param1 is " + param1.getClass().getName());
 	}
}
